package demo.filter04;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;

import java.io.IOException;

@WebFilter(filterName = "CharactorFilter", urlPatterns = "/*",
initParams = {@WebInitParam(name = "encoding", value = "UTF-8") })
public class CharactorFilter implements Filter {
    // 字符编码
    String encoding = null;
    // 初始化方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取初始化参数
        encoding = filterConfig.getInitParameter("encoding");
    }
    // 过滤处理方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 判断字符编码是否为空
        if (encoding != null){
            // 设置servletRequest的编码格式
            servletRequest.setCharacterEncoding(encoding);
            // 设置servletResponse字符编码
            servletResponse.setContentType("text/html; charset=" + encoding);
        }
        // 传递给下一过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        encoding = null;
    }
}
